package com.yanyeori.framework.web.http.request.feign;

import com.yanyeori.framework.web.http.request.GeneralRequestHeader;
import com.yanyeori.framework.web.http.request.feign.context.HeaderConverterContextHolder;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Collection;
import java.util.Enumeration;
import java.util.Map;

/**
 * Feign请求拦截器（设置请求头，传递请求参数）
 * 说明：
 * 服务间进行feign调用时，不会传递请求头信息。
 * 通过实现RequestInterceptor接口，完成对所有的Feign请求,传递请求头和请求参数。
 *
 * @author chenkuan
 * @since 2021/7/29
 */
public class FeignRequestInterceptor extends GeneralRequestHeader implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate requestTemplate) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        Collection<Object> headerContexts = HeaderConverterContextHolder.getHeaderContext();

        if (attributes != null) {
            HttpServletRequest request = attributes.getRequest();
            Enumeration<String> headerNames = request.getHeaderNames();
            if (headerNames != null) {
                while (headerNames.hasMoreElements()) {
                    String name = headerNames.nextElement();
                    if (!requestTemplate.headers().containsKey(name)) {
                        requestTemplate.header(name, request.getHeader(name));
                    }
                }
            }
        }

        if (CollectionUtils.isNotEmpty(headerContexts)) {
            // 设置自定义信息到header:主要是设置自行设置的token、userId等信息，以便转发到Feign调用的服务
            Map<String, String> headersMap = contextsToHeadersMap(headerContexts);
            if (!headersMap.isEmpty()) {
                headersMap.forEach((key, value) -> {
                    if (!requestTemplate.headers().containsKey(key)) {
                        requestTemplate.header(key, value);
                    }
                });
            }
        }
    }
}